/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Panel.java
 *
 * Created on 01/09/2011, 11:18:15
 */

package ufpb.compiladores.lexico.run.GUI;

import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ufpb.compiladores.lexico.Automaton;
import ufpb.compiladores.lexico.AutomatonFactory;
import ufpb.compiladores.lexico.LexicalTable;
import ufpb.compiladores.lexico.Reader;
import ufpb.compiladores.lexico.run.HtmlGenerator;
import ufpb.compiladores.sintatico.SyntacticalAnalyzer;
import ufpb.compiladores.sintatico.SyntacticalAnalyzerFactory;

/**
 *
 * @author Sarah
 */
public class Panel extends javax.swing.JPanel {

    private Document doc = null;
    private File file = null;
    private SyntacticalAnalyzer anas = null;
    private boolean syntactical = false;

    /** Creates new form Panel */
    public Panel(boolean synt) {
    
        this.syntactical = synt;
        initComponents();
        if (!this.syntactical) {
            
            this.remove(this.jButton2);
        }
        jTable1.setDefaultRenderer(Object.class, new CellRenderer());
        jTable2.setDefaultRenderer(Object.class, new CellRenderer());
    }
    
    public Panel(File f, boolean synt) {
        
        this(synt);
        this.file = f;
        try {
            
            this.doc = DocumentBuilderFactoryImpl.newInstance()
                            .newDocumentBuilder().newDocument();
            Element e = this.doc.createElement("Root");
            this.doc.appendChild(e);
            
            Automaton auto = AutomatonFactory.getAutomaton(Instances.LEXICAL_ENVIROMENT,
                    new Reader(f));
            LexicalTable lt = auto.generateTable(this.doc, e);
            if (this.syntactical) {
                
                anas = SyntacticalAnalyzerFactory.createSyntacticalAnalyzer(
                        Instances.SYNTACTICAL_ENVIROMENT, lt);
                
                Document doc2 = DocumentBuilderFactoryImpl.newInstance()
                            .newDocumentBuilder().newDocument();
                Element d = doc2.createElement("Syntactical");
                anas.processEnviroment(doc2, d);
            }            
            
            this.preencheTextArea();
            this.preencheNomeDoArquivo(this.file.getAbsolutePath());
            this.updateEnviroment();
        } catch (Exception ex) {
            
        }
    }

    private void updateEnviroment() {
        
        //Node fc = doc.getFirstChild();
        NodeList nl = doc.getElementsByTagName("Lexical");
        Node fc = nl.item(0);
        
        if (fc.getNodeName().equals("Lexical")) {
            NodeList root2 = fc.getChildNodes();
            Node filho1 = root2.item(0);
            Node filho2 = root2.item(1);
            String filhoo = filho1.getNodeName();
            String filhoo2 = filho2.getNodeName();
            if(filhoo.equals("Tabela")){
                NodeList listaElementos1 = filho1.getChildNodes();
                int len = listaElementos1.getLength();
                for(int m=0; m<len; m++){
                    Node aux = listaElementos1.item(m);
                    if(aux != null){
                        Node retorno = aux.getAttributes().getNamedItem("token");
                        Node retornod = aux.getAttributes().getNamedItem("descricao");
                        Node retornol = aux.getAttributes().getNamedItem("linha");
                        this.preencheLinhaTabela(new Object[] {
                                                     retorno.getTextContent(),
                                                     retornod.getTextContent(),
                                                     retornol.getTextContent()
                                                });
                    }
                }

            }
            if(filhoo2.equals("Erros")){
                NodeList listaErros = filho2.getChildNodes();
                int len = listaErros.getLength();
                for(int n=0; n<len; n++){
                    Node aux = listaErros.item(n);
                    if(aux != null){
                        Node retorno = aux.getAttributes().getNamedItem("erro");
                        Node retornol = aux.getAttributes().getNamedItem("linha");
                        System.out.println(retornol.getTextContent().toString());
                        this.preencheLinhaErro(new Object[] {
                                                    
                                                retorno.getTextContent(),
                                                retornol.getTextContent()
                                              });
                    }
                }
            }
        }
    }

    public void setTabbedNumber(int i){

        jLabel5.setText(Integer.toString(i));
        jLabel5.setVisible(false);
    }

    private void preencheLinhaTabela(Object[] obj){

         DefaultTableModel modelo = (DefaultTableModel)((jTable2).getModel());
         modelo.addRow(obj);
    }

    private void preencheLinhaErro(Object[] obj){

         DefaultTableModel modelo = (DefaultTableModel)((jTable1).getModel());
         modelo.addRow(obj);
    }

    private void preencheTextArea() {

        FileReader lerArquivo = null;
        BufferedReader bReader = null;
        try {
            
            StringBuilder sb = new StringBuilder();
            lerArquivo = new FileReader(this.file);
            bReader = new BufferedReader(lerArquivo);

            int i=1;
            String linha;
            linha = bReader.readLine();

            while(linha != null){
                sb.append(i).append(" ").append(linha).append("\n");
                i+=1;
                linha = bReader.readLine();
            }

            jTextArea1.setText(sb.toString());
            //jTextArea1.setEditable(false);
        } catch (Exception e) {
            
        } finally {
        
            try {
                
                if (bReader != null) {

                    bReader.close();
                }
            } catch (Exception e) {}
            
            try {
                
                if (lerArquivo != null) {

                    lerArquivo.close();
                }
            } catch(Exception e) {}
        }
    }

    private String removeNumbers(String srt) {
        
        String[] lines = srt.split("\n");
        StringBuilder sb = new StringBuilder();
        for (String s: lines) {
            
            sb.append(s.replaceAll("^[0-9]+ ", "")).append('\n');
        }
        
        return sb.toString();
    }
    private void preencheNomeDoArquivo(String s){

        jLabel4.setText(s);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(1100, 650));

        jLabel1.setText("Código");

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel2.setText("Tabela de Classificação");

        jLabel3.setText("Tabela de Erros");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Erro", "Linha"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(1);

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Token", "Classificação", "Linha"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setResizable(false);
        jTable2.getColumnModel().getColumn(1).setResizable(false);
        jTable2.getColumnModel().getColumn(2).setResizable(false);
        jTable2.getColumnModel().getColumn(2).setPreferredWidth(1);

        jButton1.setText("Gerar HTML");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Gerar fluxo gráfico");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Atualizar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(234, 234, 234)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(55, 55, 55)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(78, 78, 78))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addGap(20, 20, 20)
                        .addComponent(jButton1)
                        .addGap(11, 11, 11)
                        .addComponent(jButton2)))
                .addGap(36, 36, 36))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton2)
                            .addComponent(jButton3)
                            .addComponent(jButton1))))
                .addContainerGap(92, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //gerar html

        int indice = Integer.parseInt(jLabel5.getText());

        HtmlFileFilter filter = new HtmlFileFilter();
        JFileChooser fc = new JFileChooser();
        fc.setFileFilter(filter);
        int returnVal = fc.showSaveDialog(null);

            if(returnVal == JFileChooser.APPROVE_OPTION) {
                File local = fc.getCurrentDirectory();
                File arquivo = fc.getSelectedFile();

                File out = new File(local, arquivo.getName()+".html");
                //String html = HtmlGenerator.generateHtml(doc[indice], file[indice]);
                FileOutputStream fos = null;
                try {

                    fos = new FileOutputStream(out);
                    //fos.write(html.getBytes());
                    fos.flush();
                    fos.close();

                } catch (Exception ex) {
                    Logger.getLogger(Panel.class.getName()).log(Level.SEVERE, null, ex);
                }
                JOptionPane.showMessageDialog(this, "Arquivo salvo com sucesso.");

                }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
        if (this.anas !=  null) {
            
            JDialog d = new JDialog();
            d.setModal(true);
            Component co = this.anas.getSyntaticalTree().getComponent();
            d.getContentPane().add(co);
            //d.pack();

           // d.setSize(co.getHeight(), co.getWidth());

            d.setSize(1100,650);
            d.setVisible(true);
            d.setLocationRelativeTo(null);
        }        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        
        try {
            
            this.doc = DocumentBuilderFactoryImpl.newInstance()
                            .newDocumentBuilder().newDocument();
            Element e = this.doc.createElement("Lexical");
            this.doc.appendChild(e);
            File f = File.createTempFile("lexical", ".lexical");
            DataOutputStream dous = new DataOutputStream(new FileOutputStream(f));
            //dous.writeUTF(this.jTextArea1.getText());
            //dous.writeBytes(this.jTextArea1.getText());
            dous.writeBytes(this.removeNumbers(this.jTextArea1.getText()));
            dous.flush();
            dous.close();
            
            Automaton auto = AutomatonFactory.getAutomaton(Instances.LEXICAL_ENVIROMENT,
                    new Reader(f));
            LexicalTable lt = auto.generateTable(this.doc, e);
            if (this.syntactical) {
                
                anas = SyntacticalAnalyzerFactory.createSyntacticalAnalyzer(
                        Instances.SYNTACTICAL_ENVIROMENT, lt);
                Element d = this.doc.createElement("Syntactical");
                anas.processEnviroment(doc, d);
            }            
            this.updateEnviroment();
        } catch (Exception ex) {
            
        }
    }//GEN-LAST:event_jButton3ActionPerformed

        private class HtmlFileFilter extends FileFilter{

        @Override
        public boolean accept(File pathname) {

            if((pathname.getName().endsWith("html"))|| pathname.isDirectory()){
                return true;
            }
            else {
                return false;
            }
        }


        @Override
        public String getDescription() {
            return ("*.html");
        }
    }

    public class CellRenderer extends DefaultTableCellRenderer {


    private static final long   serialVersionUID    = 1L;

        public CellRenderer()
        {
            super();
        }

        @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        this.setHorizontalAlignment(CENTER);

        return super.getTableCellRendererComponent(table, value, isSelected,
                hasFocus, row, column);
    }
}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables

}
